package com.neuedu.mvc.filter;

import javax.servlet.*;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.Enumeration;
import java.util.Objects;


//@WebFilter(filterName = "LoginFilter",urlPatterns = "/*")
public class LoginFilter implements Filter {


    //忽略 的  地址，不需要登录 也得放行
    String igonreUrl[] = {"/login","/login.jsp"};
    //忽略的扩展名
    String igonreExt[] = {".css",".png",".gif",".jpg"};



    public void init(FilterConfig config) throws ServletException {


    }

    public void destroy() {
        System.out.println("CharsetEncodingFilter.destroy");
    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws ServletException, IOException {


        HttpServletRequest req = (HttpServletRequest) request;
        HttpServletResponse resp = (HttpServletResponse) response;
        HttpSession session = req.getSession();
        String username = (String) session.getAttribute("username");
        boolean pass = false;




        //登录的放行
        if(!Objects.isNull(username)  ){
            pass = true;
        }

        //如果没登录，检查是否应该放行的url   /login    /login.jsp  /web05/css/login.css"
        if(!pass){
            String requestURI = req.getRequestURI();  //    /web05//sdfsafasfasfasdf/login    /web05/login.jsp
            requestURI = requestURI.substring(requestURI.lastIndexOf("/"));   //      /login    /login.jsp    /login.css

            String ext = requestURI.contains(".")? requestURI.substring(requestURI.lastIndexOf(".")):"";  //.jsp    .css
            for (String s : igonreUrl) {
                if(s.equals(requestURI)){
                    pass = true;//找到允许放行的url
                    break;
                }
            }

            if(!pass){
                for (String extItem : igonreExt) {
                    if(extItem.equals(ext)){
                        pass = true;//找到允许放行的url
                        break;
                    }
                }
            }

        }
        //放行
        if(pass) {// 放行
            chain.doFilter(request, response);
        }else{//不允许放行 ，重定向到登录页面
            String target = req.getRequestURL().toString();

            target += "?"+req.getQueryString();

            //使用URL进行编码
            target = URLEncoder.encode(target, "utf-8");

            resp.sendRedirect(req.getContextPath()+"/login.jsp?target="+target);
        }
    }
}
